package com.mayn.action;


import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.plugin.activerecord.Db;
import com.mayn.api.KdniaoApi;
import com.mayn.util.DateUtil;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class KdniaoAction {

	private static final Logger LOG = LoggerFactory.getLogger(KdniaoAction.class);

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
	}
	
	/*
	 * State:2-在途中,3-签收,4-问题件,0-待订阅
	 * 
	 * Trace			
	 * AcceptTime		String	时间	R
	 * AcceptStation	String	描述	R
	 * Remark			String	备注	O
	 * 
	 * 
	 */

	
	/**
	 * 快递鸟推送接收，参考http://www.kdniao.com/DingyueAPI.aspx
	 * @param EBusinessID
	 * @param PushTime
	 * @param Count
	 * @param Datas
	 * @return
	 */
	public static JSONObject KdniaoApply(String EBusinessID,String PushTime,String Count,String Datas) {
		// 返回值Json对象
		JSONObject ret = new JSONObject();
		try{
			ret.put("EBusinessID", KdniaoApi.EBusinessID);
			int IntCount = Integer.parseInt(Count); 
			JSONArray Data = JSONArray.fromObject(Datas);
			if (IntCount > 0 && Data.size() > 0) {
				for (int i = 0; i < Data.size(); i++) {
					JSONObject item = Data.getJSONObject(i);
					saveExpressInfo(item);
				}
				ret.put("UpdateTime", DateUtil.dateFmtToString(new Date()));
				ret.put("Success", "true");
				ret.put("Reason", "");
			} else {
				ret.put("UpdateTime", DateUtil.dateFmtToString(new Date()));
				ret.put("Success", "false");
				ret.put("Reason", "没有快递信息要推送");
				return ret;
			}
		}
		catch(Exception e){
			LOG.error(e.getMessage());
			ret.put("UpdateTime", DateUtil.dateFmtToString(new Date()));
			ret.put("Success", "false");
			ret.put("Reason", "未知错误");
		}
		return ret;
	}
	
	/**
	 * 单条快递信息订阅
	 * @param ShipperCode
	 * @param LogisticCode
	 * @return
	 */
	public static Boolean SubscribeExpressInfo(String ShipperCode, String LogisticCode) {
		
		//单条快递信息订阅,先订阅再保存到数据库
		JSONArray dataArray = new JSONArray();
		JSONObject dataObject = new JSONObject();
		
		JSONArray itemArray = new JSONArray();
		JSONObject itemObject = new JSONObject();
		itemObject.put("Bk","");
		itemObject.put("No",LogisticCode);
		itemArray.add(itemObject);
		
		dataObject.put("Code", ShipperCode);
		dataObject.put("Item", itemArray);
		
		dataArray.add(dataObject);
		
		KdniaoApi api = new KdniaoApi();
		try {
			int c = checkExpressOrder(ShipperCode,LogisticCode);
			int state = 0;
			if(c>0){
				state = getExpressOrderState(ShipperCode,LogisticCode);
			}
			if(c ==0 || state==0){	
				String result = api.orderTracesSubByJson(dataArray);
				JSONObject jo = JSONObject.fromObject(result);
				if(jo.containsKey("Success") && jo.getString("Success").equals("true")){
					LOG.info("快递信息订阅返回成功:" + result);
					if( saveExpressOrder(ShipperCode,LogisticCode)){
						LOG.info("快递记录添加成功:ShipperCode=" + ShipperCode +",LogisticCode=" + LogisticCode);
						return true;
					}else{
						//仍然返回true
						return true;
					}
				}else{
					LOG.info("快递信息订阅返回失败:" + result);
					return false;
				}
			}else{
				LOG.info("快递信息已订阅:ShipperCode=" + ShipperCode +",LogisticCode=" + LogisticCode);
				//仍然返回true
				return true;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage());
			return false;
		}
		
	}
	
	/**
	 * 本地快递信息查询，如果不存在，先订阅，临时返回
	 * @param ShipperCode
	 * @param LogisticCode
	 * @return
	 */
	public static JSONObject getLocalExpressInfo(String ShipperCode, String LogisticCode) {
		JSONObject dataObject = new JSONObject();
		dataObject.put("EBusinessID", KdniaoApi.EBusinessID);
		dataObject.put("ShipperCode", ShipperCode);
		dataObject.put("Success", "true");
		dataObject.put("LogisticCode", LogisticCode);
		try {
			int c = checkExpressOrder(ShipperCode,LogisticCode);
			int state = 0;
			if(c>0){
				state = getExpressOrderState(ShipperCode,LogisticCode);
			}else{
				if(SubscribeExpressInfo(ShipperCode,LogisticCode)){
					dataObject.put("Reason","此单第一次订阅成功,请稍后再查询");
					dataObject.put("Traces","[]");
					LOG.info("此单第一次订阅成功,请稍后再查询:ShipperCode=" + ShipperCode +",LogisticCode=" + LogisticCode);
				}else{
					dataObject.put("Reason","此单订阅失败,请稍后再尝试");
					dataObject.put("Traces","[]");	
					LOG.info("此单订阅失败,请稍后再尝试:ShipperCode=" + ShipperCode +",LogisticCode=" + LogisticCode);
				}
			}
			if(state!=0){
				String Traces = getExpressOrderTraces(ShipperCode,LogisticCode);
				dataObject.put("State",state);
				dataObject.put("Traces",Traces);
				LOG.info("查询成功:ShipperCode=" + ShipperCode +",LogisticCode=" + LogisticCode);
			}else{
				dataObject.put("Reason","此单已订阅,请稍后再查询");
				dataObject.put("Traces","[]");
				LOG.info("此单已订阅,请稍后再查询:ShipperCode=" + ShipperCode +",LogisticCode=" + LogisticCode);
			}
			return dataObject;
		} catch (Exception e) {
			LOG.error("未知错误" + e.getMessage());
			dataObject.put("Reason","未知错误");
			dataObject.put("Traces","[]");
			return JSONObject.fromObject("{}");
		}
	}
	

	public static Boolean saveExpressInfo(JSONObject jo) {
		@SuppressWarnings("unused")
		String EBusinessID = jo.getString("EBusinessID");
		String ShipperCode = jo.getString("ShipperCode");
		String LogisticCode = jo.getString("LogisticCode");
		String Success = jo.getString("Success");
		String State = jo.getString("State");
		JSONArray Traces = jo.getJSONArray("Traces");
		if (Success.equals("true")) {
			if(Traces.toString().length()>=20000){
				LOG.error("路由信息长度超出限制:" + ShipperCode + "--" + LogisticCode + "--" + Traces.toString());
			}
			//获取揽收时间和签收时间
			String Trans_Start_Time = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(new Date(0));
			String Trans_Sign_Time = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss").format(new Date(0));
			if(!State.equals("0") && Traces.size()>0){
				Trans_Start_Time = Traces.getJSONObject(0).getString("AcceptTime");
			}
			if(State.equals("3")){
				Trans_Sign_Time = Traces.getJSONObject(Traces.size() - 1).getString("AcceptTime");
			}
			saveExpressOrder(ShipperCode,LogisticCode,State,Traces.toString(),"",Trans_Start_Time,Trans_Sign_Time);
			LOG.info("快递信息保存成功:" + ShipperCode + "--" + LogisticCode + "--" + Success + "--" + State + "--");//+ Traces.toString());
		} else {
			LOG.error("快递信息保存失败:" + ShipperCode + "--" + LogisticCode);
			return false;
		}
		return true;
	}
	
	public static int checkExpressOrder(String ShipperCode, String LogisticCode) {
		String sql = "select count(*) from express_info_sync where 1=1 AND EIS_NO='" + LogisticCode + "' AND EIS_POST_TYPE='" + ShipperCode + "'";
		return Integer.parseInt(Db.queryLong(sql).toString());
	}
	
	public static int getExpressOrderState(String ShipperCode, String LogisticCode) {
		String sql = "select EIS_STATE  from express_info_sync where 1=1 AND EIS_NO='" + LogisticCode + "' AND EIS_POST_TYPE='" + ShipperCode + "'";
		return Db.queryInt(sql);
	}
	
	public static String getExpressOrderTraces(String ShipperCode, String LogisticCode) {
		String sql = "select EIS_TRACES  from express_info_sync where 1=1 AND EIS_NO='" + LogisticCode + "' AND EIS_POST_TYPE='" + ShipperCode + "'";
		return Db.queryStr(sql);
	}
	
	public static Boolean deleteExpressOrder(String ShipperCode, String LogisticCode) {
		String sql = "update express_info_sync set EIS_DEL = 1 where 1=1 AND EIS_NO='" + LogisticCode + "' AND EIS_POST_TYPE='" + ShipperCode + "'";
		int c = Db.update(sql);
		if(c>0){
			return true;
		}else{
			return false;
		}
	}
	
	public static boolean saveExpressOrder(String ShipperCode, String LogisticCode) {
		return saveExpressOrder(ShipperCode,LogisticCode,"0","","","0000-00-00 00:00:00","0000-00-00 00:00:00");
	}
	public static boolean saveExpressOrder(String ShipperCode, String LogisticCode,String State,String Traces,String Reason,String Trans_Start_Time,String Trans_Sign_Time) {
		try{
			int c = checkExpressOrder(ShipperCode,LogisticCode);
			/*
			String insertSql = "INSERT INTO `express_info_sync` (`EIS_NO`, `EIS_POST_TYPE`, `EIS_STATE`, `EIS_TRACES`, `EIS_REASON`,`EIS_TRANS_START_TIME`,`EIS_TRANS_SIGN_TIME`, `EIS_DEL`, `EIS_CREATE_DATETIME`, `EIS_CREATE_EMPLOYEE_NAME`)" 
					+ " VALUES ("
					+ " '" + LogisticCode + "'"
					+ ",'" + ShipperCode + "'"
					+ ",'" + State + "'"
					+ ",'" + Traces + "'"
					+ ",'" + Reason + "'"
					+ ",'" + Trans_Start_Time + "'"
					+ ",'" + Trans_Sign_Time + "'"
					+ ",0"
					+ ",now()"
					+ ",'creator'"
					+ " );";
			String	updateSql = "update `express_info_sync` set " 
					+ " EIS_STATE = '" + State + "'"
					+ ",EIS_TRACES = '" + Traces + "'"
					+ ",EIS_REASON = '" + Reason + "'"
					+ ",EIS_TRANS_START_TIME = '" + Trans_Start_Time + "'"
					+ ",EIS_TRANS_SIGN_TIME = '" + Trans_Sign_Time + "'"
					+ ",EIS_UPDATE_DATETIME = now()"
					+ ",EIS_UPDATE_EMPLOYEE_NAME = 'updator'"
					+ " where EIS_NO='" + LogisticCode +"'" ;
			*/
			String insertSql = "INSERT INTO `express_info_sync` (`EIS_NO`, `EIS_POST_TYPE`, `EIS_STATE`, `EIS_TRACES`, `EIS_REASON`,`EIS_TRANS_START_TIME`,`EIS_TRANS_SIGN_TIME`, `EIS_DEL`, `EIS_CREATE_DATETIME`, `EIS_CREATE_EMPLOYEE_NAME`)" 
					+ " VALUES (?,?,?,?,?,?,? "
					+ ",0"
					+ ",now()"
					+ ",'creator'"
					+ " );";
			String	updateSql = "update `express_info_sync` set " 
					+ " EIS_STATE = ? "
					+ ",EIS_TRACES = ? "
					+ ",EIS_REASON = ? "
					+ ",EIS_TRANS_START_TIME = ? "
					+ ",EIS_TRANS_SIGN_TIME = ? "
					+ ",EIS_UPDATE_DATETIME = now()"
					+ ",EIS_UPDATE_EMPLOYEE_NAME = 'updator'"
					+ " where EIS_NO='" + LogisticCode +"'" ;
			
			if(c >0){
				Db.update(updateSql,State,Traces,Reason,Trans_Start_Time,Trans_Sign_Time);
				return true;
			}else{
				Db.update(insertSql,LogisticCode,ShipperCode,State,Traces,Reason,Trans_Start_Time,Trans_Sign_Time);
				return true;
			}
		}
		catch(Exception e){
			LOG.error(e.getMessage());
			return false;
		}
	}
}
